package com.itheima.reggie.controller;

import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.User;
import com.itheima.reggie.service.UserService;
import com.itheima.reggie.utils.SMSUtils;
import com.itheima.reggie.utils.ValidateCodeUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {

   @Autowired(required = false)
   private UserService userService;

   @Autowired(required = false)
   private RedisTemplate redisTemplate;

    @PostMapping("/sendMsg")
    public R<String> sendMsg(@RequestBody User user){
        String phone = user.getPhone();
        String code = ValidateCodeUtils.generateValidateCode(4).toString();

//        SMSUtils.sendMessage("黑马旅游网","SMS_205126318",phone,code);
        log.info("===本次验证码==="+code);

        redisTemplate.opsForValue().set(phone,code,1, TimeUnit.MINUTES);

        return R.success("验证码发送成功");

    }

    @PostMapping("/login")
    public R<User> login(@RequestBody Map<String,String> param,HttpSession session){
        String phone = param.get("phone");
        String code = param.get("code");
        String codeInSession = (String) redisTemplate.opsForValue().get(phone);

        User user = userService.login(phone,code,codeInSession);
        if(user != null){
            redisTemplate.delete(phone);
            session.setAttribute("user",user.getId());
        }else {
            return R.error("登录失败");
        }

        return R.success(user);

    }

    @PostMapping("/loginout")
    public R<String> loginOut(HttpSession session){
        session.invalidate();
        return R.success("用户退出成功");
    }
}
